/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.authority.controller;

import com.wallellen.authority.domain.Action;
import com.wallellen.authority.domain.Actiontree;
import com.wallellen.authority.service.ActionServiceInterface;
import com.wallellen.core.page.RequestMode;
import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.web.WebUtils;
import com.wallellen.web.easy.EasyUiTreeNode;
import com.wallellen.web.easy.EasyUiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by walle on 12/12/15.
 */
@RequestMapping({"/actiontree"})
@Controller
public class ActiontreeController extends WebUtils {
    private static final Logger log = LoggerFactory.getLogger(ActiontreeController.class);

    @Resource
    ActionServiceInterface actionServiceImpl;

    @RequestMapping({"/list"})
    public ModelAndView index(HttpSession session) {
        return ViewMode.getInstance().returnModelAndView(
                "authority/ActiontreeResult");
    }

    @RequestMapping({"/icons"})
    public ModelAndView icons(HttpSession session) {
        return ViewMode.getInstance().returnModelAndView(
                "authority/ActionCssIcon");
    }

    @RequestMapping({"/actionsPage"})
    public ModelAndView actionsPage(HttpSession session) {
        return ViewMode.getInstance().returnModelAndView(
                "authority/ActionChoose");
    }

    @RequestMapping({"/treePage"})
    public ModelAndView treePage(HttpSession session, String ids) {
        return ViewMode.getInstance().putAttr("ids", ids)
                .returnModelAndView("authority/ActiontreenodeChooseTreeWin");
    }

    @RequestMapping({"/query"})
    @ResponseBody
    public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            if (query.getQueryRule().size() == 0) {
                query.addRule(new DBRule("PARENTID", "NONE", "="));
            }
            DataResult result = this.actionServiceImpl.createActiontreeSimpleQuery(
                    query).search();
            result.runDictionary("1:分类,2:菜单,3:权限", "TYPE");
            result.runDictionary("1:可用,0:禁用", "STATE");
            return ViewMode.getInstance()
                    .putAttrs(EasyUiUtils.formatGridData(result))
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/queryMenu"})
    @ResponseBody
    public Map<String, Object> loadAllMenu() {
        try {
            DataQuery query =
                    DataQuery.getInstance(
                            1,
                            "ACT_TREE.NAME AS NAME, ACT_KEY.AUTHKEY AS SRCKEY, ACT_TREE.ID AS ID,ACT_TREE.PARENTID AS PARENTID",
                            "alone_auth_actiontree AS act_tree left join  alone_auth_action AS act_key on act_tree.ACTIONID=act_key.ID");
            query.setPagesize(100);
            return ViewMode.getInstance()
                    .putAttrs(EasyUiUtils.formatGridData(query.search()))
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/edit"})
    @ResponseBody
    public Map<String, Object> editSubmit(Actiontree entity, Action action, HttpSession session) {
        try {
            entity = this.actionServiceImpl.editActiontreeEntity(entity,
                    getCurrentUser(session), action.getAuthkey());

            return ViewMode.getInstance().putAttr("entity", entity)
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/add"})
    @ResponseBody
    public Map<String, Object> addSubmit(Actiontree entity, String authkey, HttpSession session) {
        try {
            entity = this.actionServiceImpl.insertActiontreeEntity(entity,
                    getCurrentUser(session), authkey);
            return ViewMode.getInstance().putAttr("entity", entity)
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/del"})
    @ResponseBody
    public Map<String, Object> delSubmit(String ids, HttpSession session) {
        try {
            for (String id : parseIds(ids)) {
                this.actionServiceImpl.deleteActiontreeEntity(id,
                        getCurrentUser(session));
            }
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/form"})
    public ModelAndView view(RequestMode pageset, String domain, String ids, String parentid) {
        ViewMode mode = ViewMode.getInstance();
        try {
            Actiontree parent = new Actiontree();
            Actiontree entity = null;
            switch (pageset.getOperateType()) {
                case 1:
                    break;
                case 0:
                    entity = this.actionServiceImpl.getActiontreeEntity(ids);
                    mode.putAttr("entity", entity);
                    break;
                case 2:
                    entity = this.actionServiceImpl.getActiontreeEntity(ids);
                    mode.putAttr("entity", entity);
                    break;
            }

            if ((parentid != null) && (parentid.trim().length() > 0)) {
                parent = this.actionServiceImpl.getActiontreeEntity(parentid);
                mode.putAttr("parent", parent);
            }
            if ((entity != null) && (entity.getActionid() != null)) {
                Action treeAction = this.actionServiceImpl.getActionEntity(entity
                        .getActionid());
                mode.putAttr("treeAction", treeAction);
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e + e.getMessage())
                    .returnModelAndView("authority/ActiontreeForm");
        }
        return mode.putAttr("pageset", pageset).putAttr("domain", domain)
                .returnModelAndView("authority/ActiontreeForm");
    }

    @RequestMapping({"/move"})
    @ResponseBody
    public Map<String, Object> moveTreeNodeSubmit(String oid, String deid) {
        try {
            this.actionServiceImpl.moveActionTreeNode(oid, deid);
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/loadtree"})
    @ResponseBody
    public List<EasyUiTreeNode> loadTreeNode(String id, String domain) {
        try {
            return this.actionServiceImpl.getSyncTree(id, domain);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return new ArrayList();
    }

    @RequestMapping({"/cuserMenus"})
    @ResponseBody
    public Object loadTreeNodeForCurrentUser(String id, String domain, HttpSession session) {
        try {
            List list1 =
                    EasyUiTreeNode.queryTreeNodeOne(
                            id,
                            "SORT",
                            "(SELECT c.NAME    AS NAME, SORT, c.ID      AS ID,  PARENTID, ICON, b.AUTHKEY     AS URL, c.PARAMS  AS PARAM, domain FROM alone_auth_actiontree c LEFT JOIN alone_auth_action b ON c.ACTIONID = b.ID)",
                            "ID", "PARENTID", "NAME", "ICON",
                            "and a.DOMAIN='" + domain + "'", "URL,PARAM")
                            .getResultList();
            List list2 = EasyUiTreeNode.queryTreeNodeTow(
                    id, "SORT", "alone_auth_actiontree", "ID", "PARENTID",
                    "NAME", "ICON", "and a.DOMAIN='" + domain + "'")
                    .getResultList();
            return EasyUiTreeNode.formatAsyncAjaxTreeForMenuTree(list1, list2,
                    "PARENTID", "ID", "NAME", "ICON", "URL", "PARAM",
                    getCurrentUserMenus(session));
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }
}